//
//  CalarViewController.m
//  TimeTest
//
//  Created by LvJianfeng on 16/7/21.
//  Copyright © 2016年 LvJianfeng. All rights reserved.
//

#import "CalendarViewController.h"
#import "NSDate+Formatter.h"

#define LL_SCREEN_WIDTH  ([UIScreen mainScreen].bounds.size.width)
#define LL_SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define Iphone6Scale(x) ((x) * LL_SCREEN_WIDTH / 375.0f)

#define HeaderViewHeight 30
#define WeekViewHeight   40

@interface CalendarViewController () <UICollectionViewDelegate, UICollectionViewDataSource>
@property (strong, nonatomic) NSMutableArray   *dayModelArray;
@property (nonatomic, strong) UILabel          *dateLabel; // 年-月
@property (nonatomic, strong) UIButton         *beforeButton;
@property (nonatomic, strong) UIButton         *nextButton;
@property (strong, nonatomic) NSDate           *tempDate;
@property (nonatomic, strong) UILabel          *selectDateLabel; // 年 - 月 - 日
@property (nonatomic,strong)  NSArray   *weekArr;
@end

@implementation CalendarViewController

- (void)beforeMonthClick {
    self.tempDate       = [self getLastMonth:self.tempDate];
    self.dateLabel.text = self.tempDate.yyyyMMByLineWithDate;
    [self getDataDayModel:self.tempDate];
}

- (void)nextMonthClick {
    if (self.tempDate.year==[NSDate date].year && self.tempDate.month==[NSDate date].month) {
         SHOWMBProgressHUD(nil,SN_Text(@"不能选择未来时间！"), nil, NO, 1.0);
         return;
    }
    self.tempDate       = [self getNextMonth:self.tempDate];
    self.dateLabel.text = self.tempDate.yyyyMMByLineWithDate;
    [self getDataDayModel:self.tempDate];
}

- (void)reloadViewData
{
    [self.collectionView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _weekArr = [[NSArray alloc] initWithObjects:SN_Text(@"周日"), SN_Text(@"周一"), SN_Text(@"周二"), SN_Text(@"周三"), SN_Text(@"周四"), SN_Text(@"周五"), SN_Text(@"周六"), nil];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];
    
    [self.view addSubview:self.collectionView];
    self.collectionView.layer.cornerRadius = 8.0;
    self.collectionView.layer.masksToBounds = YES;
    backView.layer.cornerRadius = 8.0;
    backView.layer.masksToBounds = YES;
    backView.frame = self.collectionView.frame;
    
    UIButton *back = [[UIButton alloc] init];
    back.frame = SNFRAME(0, 0, LL_SCREEN_WIDTH, 64);
    [self.view addSubview:back];
    [back addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIView *selectView = [[UIView alloc] initWithFrame:SNFRAME(0, 64, LL_SCREEN_WIDTH, 50)];
    selectView.backgroundColor = SNCOLORBLACK;
    [self.view addSubview:selectView];
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:selectView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(8, 8)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = selectView.bounds;
    maskLayer.path = maskPath.CGPath;
    selectView.layer.mask = maskLayer;
    
    UIView *emptyView = [[UIView alloc] initWithFrame:SNFRAME(0, 64 +50, LL_SCREEN_WIDTH, 40)];
    emptyView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:emptyView];
    
    _selectDateLabel               = [[UILabel alloc] init];
    _selectDateLabel.textColor     = [UIColor whiteColor];
    _selectDateLabel.font          = SNFONT(25.0);
    _selectDateLabel.textAlignment = NSTextAlignmentCenter;
    _selectDateLabel.frame         = SNFRAME(0, 64, LL_SCREEN_WIDTH, 50);
    _selectDateLabel.text          =[NSString stringWithFormat:@"%@ %@",[SN_PublicClass.selectDate dateToDayString],_weekArr[SN_PublicClass.selectDate.weekday-1]];
    [self.view addSubview:_selectDateLabel];
    
    _dateLabel               = [[UILabel alloc] init];
    _dateLabel.textColor     = SNCOLORBLACK;
    _dateLabel.font          = SNFONT(17.0);
    _dateLabel.textAlignment = NSTextAlignmentCenter;
    _dateLabel.frame         = SNFRAME(0, 10 + 64 + 50, LL_SCREEN_WIDTH, 20);
    [self.view addSubview:_dateLabel];
    
    _beforeButton       = [UIButton buttonWithType:UIButtonTypeCustom];
    _beforeButton.frame = CGRectMake(20, +64 +50, 80, 40);
    [_beforeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_beforeButton setImageNormal:@"三角形左"];
    [_beforeButton addTarget:self action:@selector(beforeMonthClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_beforeButton];
    
    _nextButton       = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextButton.frame = CGRectMake(HHHWIDTH - 100, +64+50, 80, 40);
    [_nextButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_nextButton setImageNormal:@"三角形右"];
    [_nextButton addTarget:self action:@selector(nextMonthClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextButton];
    
    self.tempDate       = SN_PublicClass.selectDate;
    self.dateLabel.text = self.tempDate.yyyyMMByLineWithDate;
//    NSArray *array = [self.tempDate.yyyyMMByLineWithDate componentsSeparatedByString:@"-"];
//    self.dateLabel.text = [NSString stringWithFormat:@"%@%@%@%@",[array firstObject],SN_Text(@"年"),[array lastObject],SN_Text(@"月")];
    
    [self getDataDayModel:self.tempDate];
}

- (void)backClick {
    if (_cancelBlock) {
        _cancelBlock();
    }
}

- (void)getDataDayModel:(NSDate *)date {
    NSUInteger days = [self numberOfDaysInMonth:date];
    NSInteger  week = [self startDayOfWeek:date];
    
    self.dayModelArray = [[NSMutableArray alloc] initWithCapacity:42];
    int day = 1;
    for (int i = 1; i < days+week; i++) {
        if (i < week) {
            [self.dayModelArray addObject:@""];
        } else {
            MonthModel *mon = [MonthModel new];
            mon.dayValue = day;
            NSDate *dayDate = [self dateOfDay:day];
            mon.dateValue = dayDate;
            if ([dayDate.yyyyMMddByLineWithDate isEqualToString:[NSDate date].yyyyMMddByLineWithDate]) {
                mon.isSelectedDay = YES;
            }
            [self.dayModelArray addObject:mon];
            day++;
        }
    }
    [self.collectionView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dayModelArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"CalendarCell";
    
    CalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    if (nil == cell) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CalendarCell" forIndexPath:indexPath];
    }
    
    id mon = self.dayModelArray[indexPath.row];
    cell.stepCircle.progress = 0.0;
    if ([mon isKindOfClass:[MonthModel class]]) {
        cell.monthModel = (MonthModel *)mon;
    } else {
        cell.stepCircle.hidden            = YES;
        cell.currentDateCircleView.hidden = YES;
        cell.dayLabel.text                = @"";
    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    CalendarHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"CalendarHeaderView" forIndexPath:indexPath];
    return headerView;
}

// 选中的日期
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    id mon = self.dayModelArray[indexPath.row];
    
    if ([mon isKindOfClass:[MonthModel class]]) {
        NSInteger nowCount = [NSDate compareDate:[NSDate date] withAnotherDay:[(MonthModel *)mon dateValue]];
        if (nowCount == 1) {
            SHOWMBProgressHUD(nil,SN_Text(@"不能选择未来时间！"), nil, NO, 1.0);
            return;
        }
        _selectDateLabel.text = [NSString stringWithFormat:@"%@ %@",[(MonthModel *)mon dateValue].yyyyMMddByLineWithDate,_weekArr[[(MonthModel *)mon dateValue].weekday-1]];
        if (_selectDateBlock) {
            _selectDateBlock([(MonthModel *)mon dateValue]);
        }
    }
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        NSInteger width  = Iphone6Scale(54);
        NSInteger height = 45;
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.itemSize                = CGSizeMake(self.view.width /7, height);
        flowLayout.headerReferenceSize     = CGSizeMake(LL_SCREEN_WIDTH, HeaderViewHeight);
        flowLayout.sectionInset            = UIEdgeInsetsMake(0, 0, 0, 0);
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing      = 0;
        
        CGFloat rowheight = 0;
        rowheight = FitSimpleSize(280, 300, 300, 300, 300);
        
        _collectionView                 = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64 + 40 +40, self.view.width, rowheight) collectionViewLayout:flowLayout];
        _collectionView.delegate        = self;
        _collectionView.dataSource      = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        
        [_collectionView registerClass:[CalendarCell class] forCellWithReuseIdentifier:@"CalendarCell"];
        [_collectionView registerClass:[CalendarHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CalendarHeaderView"];
    }
    
    return _collectionView;
}

#pragma mark -Private
- (NSUInteger)numberOfDaysInMonth:(NSDate *)date {
    NSCalendar *greCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    return [greCalendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
}

- (NSDate *)firstDateOfMonth:(NSDate *)date {
    NSCalendar *greCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth |NSCalendarUnitWeekday | NSCalendarUnitDay
                               fromDate:date];
    comps.day = 1;
    return [greCalendar dateFromComponents:comps];
}

- (NSUInteger)startDayOfWeek:(NSDate *)date {
    NSCalendar *greCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];//Asia/Shanghai
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth |NSCalendarUnitWeekday | NSCalendarUnitDay
                               fromDate:[self firstDateOfMonth:date]];
    return comps.weekday;
}

- (NSDate *)getLastMonth:(NSDate *)date {
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                               fromDate:date];
    comps.month -= 1;
    if (comps.day >=28 ) {
        comps.day = 28;
    }
    return [greCalendar dateFromComponents:comps];
}

- (NSDate *)getNextMonth:(NSDate *)date {
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                               fromDate:date];
    comps.month += 1;
    
    if (comps.day >=28 ) {
        comps.day = 28;
    }
    return [greCalendar dateFromComponents:comps];
}

- (NSDate *)dateOfDay:(NSInteger)day {
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                               fromDate:self.tempDate];
    comps.day = day;
    return [greCalendar dateFromComponents:comps];
}

@end

@implementation CalendarHeaderView
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        NSArray *weekArray = [[NSArray alloc] initWithObjects:@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
        
        for (int i = 0; i < weekArray.count; i++) {
            UILabel *weekLabel = [[UILabel alloc] initWithFrame:CGRectMake(i*Iphone6Scale(54), 2, Iphone6Scale(54), HeaderViewHeight)];
            weekLabel.textAlignment = NSTextAlignmentCenter;
            weekLabel.textColor     = [UIColor grayColor];
            weekLabel.font          = [UIFont systemFontOfSize:13];
            weekLabel.text          = SN_Text(weekArray[i]);
            [self addSubview:weekLabel];
            weekLabel.adjustsFontSizeToFitWidth = YES;
        }
    }
    return self;
}

@end


@implementation CalendarCell
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        //      NSInteger width = Iphone6Scale(54);
        //      NSInteger height = Iphone6Scale(54);
        //
        //        UIView *view = [[UIView alloc] init];
        //        view.frame = CGRectMake(5, 25, 30, 30);
        //        view.backgroundColor = [UIColor greenColor];
        //        view.center = self.contentView.center;
        //        [self.contentView addSubview:view];
        
        ZZCACircleProgress *stepCircle = [[ZZCACircleProgress alloc] initWithFrame:CGRectMake(0, 0, 30, 30) pathBackColor:nil pathFillColor:SNCOLORBLACK startAngle:-90 strokeWidth:2];
        stepCircle.showProgressText = YES;
        stepCircle.duration         = 0.2;//动画时长
        stepCircle.increaseFromLast = YES;
        stepCircle.pointImage.image = nil;
        stepCircle.prepareToShow    = YES;//设置好属性，准备好显示了，显示之前必须调用一次
        //        stepCircle.progress = arc4random()%100 /100;
        stepCircle.progress        = 0.0;
        stepCircle.ValueLabel.text = @"";
        stepCircle.unitLabel.text  = @"";
        stepCircle.ValueLabel.font = SNFONT(33);
        stepCircle.unitLabel.font  = SNFONT(15);
        stepCircle.hidden          = YES;
        stepCircle.center          = self.contentView.center;
        [self.contentView addSubview:stepCircle];
        self.stepCircle = stepCircle;
        
        UIView *currentDateCircleView = [[UIView alloc] initWithFrame:SNFRAME(0, 0, 28, 28)];
        currentDateCircleView.backgroundColor     = [UIColor whiteColor];
        currentDateCircleView.hidden              = YES;
        currentDateCircleView.layer.masksToBounds = YES;
        currentDateCircleView.layer.cornerRadius  = 14.0;
        currentDateCircleView.center              = stepCircle.center;
        [self.contentView addSubview:currentDateCircleView];
        self.currentDateCircleView = currentDateCircleView;
        
        UILabel *dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        dayLabel.textAlignment       = NSTextAlignmentCenter;
        dayLabel.layer.masksToBounds = YES;
        dayLabel.center              = stepCircle.center;
        dayLabel.font                = [UIFont systemFontOfSize:12.0];
        [self.contentView addSubview:dayLabel];
        self.dayLabel = dayLabel;
    }
    return self;
}

- (void)setMonthModel:(MonthModel *)monthModel {
    _monthModel        = monthModel;
    NSString *firstString = [monthModel.dateValue dateToDayString];
    self.dayLabel.text = [NSString stringWithFormat:@"%ld", monthModel.dayValue];
    
    NSString *stepS       = [NSString stringWithFormat:@"SELECT step FROM SportModel WHERE dateString ='%@' and user_id = '%@'", firstString, SN_USER.user_id];
    NSString *step        = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:stepS arguments:nil];
    NSString *stepTargetS = [NSString stringWithFormat:@"SELECT stepTarget FROM SportModel WHERE dateString ='%@' and user_id = '%@'", firstString, SN_USER.user_id];
    NSString *stepTarget  = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:stepTargetS arguments:nil];
    float progress = 1.0 *step.intValue / stepTarget.intValue;
    if (progress >= 1.0) {
        progress = 1.0;
    }
    if (progress <=0.0) {
        progress = 0.01;
    }
    //    self.stepCircle.progress = 1.0 *monthModel.dayValue /100;
    self.stepCircle.progress = progress;
    self.stepCircle.hidden = NO;
    
    if ([[[NSDate date]dateToDayString] isEqualToString:[monthModel.dateValue dateToDayString]]) {
        _currentDateCircleView.hidden          = NO;
        _dayLabel.textColor                    = [UIColor blackColor];
        _currentDateCircleView.backgroundColor = SNCOLORGRAYLINE;
    }
    else {
        _dayLabel.textColor                    = [UIColor blackColor];
        _currentDateCircleView.hidden          = YES;
        _currentDateCircleView.backgroundColor = [UIColor whiteColor];
    }
    
     if ([[SN_PublicClass.selectDate dateToDayString]isEqualToString:[monthModel.dateValue dateToDayString]])
    {
        _currentDateCircleView.hidden          = NO;
        _dayLabel.textColor                    = [UIColor whiteColor];
        _currentDateCircleView.backgroundColor = [UIColor blackColor];
    }
    [SN_PublicClass.selectDate dateToDayString];
}

@end

@implementation MonthModel

@end

